package netty.ProtoBuf.codec2;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import netty.ProtoBuf.codec.StudentPOJO;

import java.util.Random;

/**
 * @ClassName ClientHandler
 * @Description TODO
 * @Author director吴
 * @Date 2022/1/20 13:25
 * @Version 1.0
 **/
public class ClientHandler extends ChannelInboundHandlerAdapter {


    //通道 准备好了 就会触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        //发送Student对象
//        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(4).setName("豹子头林冲").build();
//        StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(4).setName("智多星").build();
//        ctx.writeAndFlush(student);


        //随机发送Student 或者 Worker

        int random =  new Random().nextInt(3);
        MyDataInfo.MyMessage  message = null;

        if (random == 0){

            message  =   MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.StudentType).
                    setStudent(MyDataInfo.Student.newBuilder().setId(5).setName("牛宝").build()).build();

        } else {
            message  =   MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.WorkerType).
                    setWorker(MyDataInfo.Worker.newBuilder().setAge(30).setName("陈老师").build()).build();

        }

        ctx.writeAndFlush(message);




    }

    //读取客户端发送的消息
    //通道有读取事件 ---  就会触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf)msg;

        System.out.println("服务器回复消息："+ byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器地址："+ctx.channel().remoteAddress());
    }


    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();;
        ctx.close();

    }
}
